let login = getCookie("login");
if (!login) {
    // 需要把当前页面的地址 存在本地存储
    localStorage.setItem("url", location.href);
    location.href = "../html/login.html";
}
class Car {
    constructor(ele, user) {
        this.ele = document.querySelector(ele);
        this.user = user;

        this.init();
    }
    init(){
        this.panelBody = this.ele.querySelector('.panel-body');
        this.kind = this.ele.querySelector('.kind');
        this.countTotal = this.ele.querySelector(".countTotal");
        this.totalPrice = this.ele.querySelector(".totalPrice");
        this.allChecked = this.ele.querySelector('#allChecked');
        

        this.getData();
        this.ele.onclick = () =>{
            let e = window.event;
            //全选
            if(e.target.id == 'allChecked'){
                this.res.forEach((item) => {
                    item.is_select = e.target.checked ? "1" : "0";
                });
            }
            //单选
            else if(e.target.className == 'checked'){
                //获取当前点击的元素的index
                let id = e.target.getAttribute("index"); //渲染时添加index
                //console.log(id);
                this.res.forEach((item) => {
                    // console.log(item.goods_id);
                    if (item.goods_id == id) { 
                        item.is_select = e.target.checked ? "1" : "0";
                    }
                });
            }
            localStorage.setItem("data", JSON.stringify(this.res));
            this.fun();

            if(e.target.classList.contains('reduce')){
                let id = e.target.parentNode.getAttribute('index');
                
                let value = e.target.nextElementSibling.innerHTML * 1 - 1;
                this.changeCount(id, value);
       
            }
            if(e.target.classList.contains('add')){
                let id = e.target.parentNode.getAttribute('index');
                
                let value = e.target.previousElementSibling.innerHTML * 1 + 1;
                this.changeCount(id, value);
            }
            //删除数据
            if(e.target.className == 'del'){
                let id = e.target.parentNode.getAttribute('index');
                // console.log(id);
                this.deleteData(id);
            }


            //结算
            if(e.target.classList.contains('settlement')){
                this.res.forEach((item)=>{
                    if(item.is_select == 1){
                        this.deleteData(item.goods_id);
                    }
                })
            }
        }
        
    }

    async getData(){
        let res = await pAjax({
            url:'../api/getCarData.php',
            type:'get',
            data:{username:this.user},
        })
        localStorage.setItem("data", res);
        this.fun();
    }

    fun(){
        this.res = JSON.parse(localStorage.getItem("data"));
        let str = '';
        this.calculation();
        this.res.forEach(function(item){
            str += `<div class="media">
            <div class="media-left media-middle">
                <label>
                    <input index="${item.goods_id}"
                        type="checkbox"
                        class="checked"
                        ${item.is_select == "1" ? "checked" : ""}
                    />
                </label>
                <a href="#">
                    <img
                        class="media-object"
                        src="${item.goods_small_logo}"
                    />
                </a>
            </div>
            <div class="media-body">
                <div class="content">
                    <h4 class="media-heading">
                       ${item.goods_name}
                    </h4>
                    <span
                        class="glyphicon glyphicon glyphicon-yen"
                        aria-hidden="true"
                    >
                        ${item.goods_price}
                    </span>
                </div>

                <div class="btn-group" index="${item.goods_id}">
                    <button type="button" ${
                        item.goods_num == 1 ? "disabled" : ""
                    } class="btn btn-default reduce">-</button>
                    <button type="button" class="btn btn-default">${
                        item.goods_num
                    }</button>
                    <button type="button" class="btn btn-default add">+</button>
                </div>

                <div class="total">
                    小计：
                    <span>￥${
                        item.goods_price * item.goods_num
                    }</span>
                </div>

                <button
                    type="button"
                    class="close del"
                    index="${item.goods_id}">
                    <span  class="del" index="${
                        item.goods_id
                    }">&times;</span>
                </button>
            </div>
        </div>`;
        });
        this.panelBody.innerHTML = str;

        
    }
    //商品种类,所选商品数量
    calculation(){
        this.kind.innerHTML = this.res.length;

        //总价格 
        this.totalPrice.innerHTML =  this.res.reduce(function(pre,item){
            if (item.is_select == "1") {
                return pre + item.goods_price * item.goods_num * 1;
            }
            return pre;
        }, 0);

        //总类型
        this.countTotal.innerHTML =  this.res.reduce(function(pre,item){
            if (item.is_select == "1") {
                return pre + item.goods_num*1;
            }
            return pre;
        }, 0);

        //当单选框全部选上时，全选框也要选上
        this.allChecked.checked = this.res.every((item) => {
            return item.is_select == "1";
        });
    }
    
    
    async changeCount(id,value){
        let res =  await pAjax({
            url:'../api/updataCar.php',
            data:{
                goods_id:id,
                goods_num:value,
                username:this.user,
            },
        })
        res = JSON.parse(res);
        console.log(res);
        if(res.code){
            this.res.forEach((item) => {
                item.goods_num = item.goods_id == id ? value : item.goods_num;
            });
        }
        localStorage.setItem("data", JSON.stringify(this.res));
        this.fun();
    }

    //操作数据库删除
    async deleteData(id){
        let res = await pAjax({
             url:'../api/deleteCar.php',
             data:{
                 username:this.user,
                 goods_id:id,
                }
        })
        res = JSON.parse(res);
        if(res.code){
            this.res = this.res.filter(function(item){
                return item.goods_id !== id  
            })
        }
        localStorage.setItem('data',JSON.stringify(this.res))
        // console.log(res);
        this.fun();
           
    }
}


new Car('.car',login);
